package com.goldcn.order.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goldcn.common.*;
import com.goldcn.common.consts.RestConst;
import com.goldcn.common.exception.ServiceException;
import com.goldcn.common.model.DataResult;
import com.goldcn.common.util.CommonUtils;
import com.goldcn.common.util.IdGen;
import com.goldcn.config.ProConstants;
import com.goldcn.enumeration.BuyerEnum;
import com.goldcn.enumeration.CommissionEnum;
import com.goldcn.enumeration.TopDeptEnum;
import com.goldcn.goods.dao.GoodsClassifyCommissionMapper;
import com.goldcn.goods.dao.GoodsInfoMapper;
import com.goldcn.goods.dao.GoodsSkuMapper;
import com.goldcn.goods.dao.OrderPartMapper;
import com.goldcn.goods.dto.QueryResultGoodsDto;
import com.goldcn.goods.model.*;
import com.goldcn.interceptor.SystemContext;
import com.goldcn.order.dao.CommissionDetailMapper;
import com.goldcn.order.dao.CommissionUserMapper;
import com.goldcn.order.dao.OrderInfoMapper;
import com.goldcn.order.dao.OrderItemMapper;
import com.goldcn.order.dto.DealDto;
import com.goldcn.order.dto.UserCommissionDto;
import com.goldcn.order.model.CommissionDetail;
import com.goldcn.order.model.CommissionUser;
import com.goldcn.order.model.OrderInfo;
import com.goldcn.order.model.OrderItem;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.primitives.Longs;
import net.sf.json.JSONObject;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by wanglq on 2017/7/21.
 */
@Service
@Transactional
@ConfigurationProperties("bank")
public class CommissionUserService {


    @Autowired
    CommissionUserMapper commissionUserMapper;
    @Autowired
    CommissionDetailMapper commissionDetailMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    GoodsClassifyCommissionMapper goodsClassifyCommissionMapper;
    @Autowired
    GoodsInfoMapper goodsInfoMapper;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    GoodsSkuMapper goodsSkuMapper;

    @Autowired
    OrderInfoMapper orderInfoMapper;

    @Autowired
    RebateService rebateService;

    @Autowired
    OrderPartMapper orderPartMapper;


    //用户数据库表配置
    private String databaseTableUser;

    private static Logger logger = LoggerFactory.getLogger(CommissionUserService.class);

    public Map<String, Object> getUserCommissionDetail(Long userID) {
       /* if(!isClazzSupply(SystemContext.getCompanyID(),restTemplate)){
            return  getUserCommissionVal(userID);
        }*/
        Map<String, Object> map = Maps.newHashMap();
        CommissionUser commissionUser = commissionUserMapper.selectByUserID(userID);
        Long total = commissionUser == null ? 0L : commissionUser.getTotal();
        BigDecimal userTotalCommission = BigDecimalUtil.div(BigDecimal.valueOf(total), BigDecimal.valueOf(1000), 2);
        map.put("userTotalCommission", userTotalCommission);
        List<Map<String, Object>> details = commissionDetailMapper.selectByUserID(userID);
        map.put("details", details);
        return map;
    }


    public Object getCommissionDetail(Long detailID) {
        return commissionDetailMapper.selectByPrimaryKey(detailID);
    }

    public Map<String, Object> getUserCommissionDetail2(Long userID) {
        return getUserCommissionVal(userID);
    }

    /**
     * 员工中收
     *
     * @param userID
     * @return
     */
    private Map<String, Object> getUserCommissionVal(Long userID) {
        Map<String, Object> map = Maps.newHashMap();
        BigDecimal userTotalCommission = orderInfoMapper.selectUserTotalCommission(userID);
        userTotalCommission = userTotalCommission == null ? BigDecimal.valueOf(0) : userTotalCommission;
        map.put("userTotalCommission", userTotalCommission);
        List<Map<String, Object>> details = orderInfoMapper.selectUserCommissions(userID, databaseTableUser);

        List<Map<String, Object>> newList = Lists.newArrayList();
        for (Map<String, Object> map1 : details) {
            if (map1.containsKey("commission")) {
                String uname = MapUtils.getString(map1, "uname", "");
                if (Strings.isNullOrEmpty(uname)) {
                    map1.put("uname", MapUtils.getString(map1, "mobile", ""));
                } else {
                    map1.put("uname", uname);
                }

                newList.add(map1);
            }
        }
        map.put("details", newList);
        return map;
    }

    /**
     * 是否开启奖金
     *
     * @param companyID
     * @param restTemplate
     * @return
     */
    public boolean isClazzSupply(Long companyID, RestTemplate restTemplate) {
        DataResult dataResult = HttpUtil.httpGet(ProConstants.isClazzSupply + companyID, restTemplate);
        if (!Objects.equal(dataResult.getIsSuccess(), 1)) {
            return false;
        }
        return Boolean.valueOf(String.valueOf(dataResult.getData()));
    }


    public boolean isAdmin(Long userID) {
        try {
            Map<String, Object> userInfo = getUserInfoWithDept(userID);
            boolean isSecondDeptAdmin = MapUtils.getBooleanValue(userInfo, "isSecondDeptAdmin", false);
            boolean isFourthDeptAdmin = MapUtils.getBooleanValue(userInfo, "isFourthDeptAdmin", false);
            return isSecondDeptAdmin || isFourthDeptAdmin;
        } catch (Exception e) {
            return false;
        } catch (Error e) {
            return false;
        }
    }

    public double getDueAmountForItem(Long userID, OrderItem item) {
        Map<String, Object> userInfo = getUserInfoWithDept(userID);
        boolean isSecondDeptAdmin = MapUtils.getBooleanValue(userInfo, "isSecondDeptAdmin", false);
        boolean isFourthDeptAdmin = MapUtils.getBooleanValue(userInfo, "isFourthDeptAdmin", false);
        if (!isSecondDeptAdmin && !isFourthDeptAdmin) {
            return item.getAmount().doubleValue();
        }
        double newAmount = 0d;
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(item.getGoodsID());
        GoodsClassifyCommission goodsClassifyCommission = getClassifyCommission(goodsInfo);
        Double proportion = 0d;
        if (isSecondDeptAdmin) {
            proportion = getProportion(goodsClassifyCommission, true, false);
        } else if (isFourthDeptAdmin) {
            proportion = getProportion(goodsClassifyCommission, false, true);
        } else {
            proportion = 1d;
        }
        newAmount = BigDecimalUtil.mul(item.getAmount(), BigDecimal.valueOf(proportion)).doubleValue();
        return newAmount;
    }

    // 计算管理者折扣（不包含市代）
    public String getcommissionRate(Long userID, Long skuID) {
        Map<String, Object> userInfo = getUserInfoWithDept(userID);
        boolean isSecondDeptAdmin = MapUtils.getBooleanValue(userInfo, "isSecondDeptAdmin", false);
        boolean isFourthDeptAdmin = MapUtils.getBooleanValue(userInfo, "isFourthDeptAdmin", false);
        //计算提成金额直接抵扣
        GoodsSku goodsSku = goodsSkuMapper.selectByPrimaryKey(skuID);
        GoodsInfo goodsInfo = goodsInfoMapper.selectByPrimaryKey(goodsSku.getGoodsID());
        GoodsClassifyCommission goodsClassifyCommission = getClassifyCommission(goodsInfo);
        Double proportion = 0d;
        if (isSecondDeptAdmin) {
            proportion = getProportion(goodsClassifyCommission, true, false);
        } else if (isFourthDeptAdmin) {
            proportion = getProportion(goodsClassifyCommission, false, true);
        } else {
            proportion = 1d;
        }
        return proportion + "";
    }


    /**
     * 奖金
     * 支付成功调用
     *
     * @param list
     */
    public void addCommissionForNoException(List<OrderInfo> list, String payNo, RestTemplate restTemplate) {
        try {
//            if (isClazzSupply(SystemContext.getCompanyID(), restTemplate)) {
//                //Double oA = orderInfoMapper.selAmountByPayNo(payNo);
//                //addCommission(list);
//            }
            addCommission(list);
        } catch (ServiceException e) {
            logger.error("奖金分配失败：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            logger.error("奖金分配失败：" + e.getMessage());
            e.printStackTrace();
        } catch (Error e) {
            logger.error("奖金分配失败：" + e.getMessage());
            e.printStackTrace();
        }
    }

    private void addCommission(List<OrderInfo> list) {
        for (OrderInfo orderInfo : list) {
            try {
                addCommissionV3(orderInfo);
            } catch (Exception e) {
                logger.error("point error", e);
                e.printStackTrace();
                logger.info(e.getMessage());
            }
        }
    }


    /**
     * 小商城成交奖金计算 2018-4-28
     * <p>
     * 计算方式  4-285-2018
     * 1. 店铺层级的奖金按照向下兼容的原则，以购买者所属的分销机构计算，即：层级高的可以拿完层级低
     * 2. 合伙人的奖金按照向上兼容的原则，以购买商城的合伙人结构计算，即：从层级低开始计算
     * 3. 消费者归属的商城与购买实际商城不一致时，计算系数参考购买的实际商城，计算分成人员参考归属的架构层级
     * <p>
     * <p>
     * <p>
     * 计算方式 4-28-2018
     * * 1. 用户直接购买： 店铺用户和供货渠道依次有提成
     * * 2. 用户间接购买： 即用户归属商城与购买商城不一致时，对购买商城的供货渠道进行提成计算
     * * 3. 6%o的手续费有购买商城负责
     *
     * @param orderInfo
     * @return
     */
    public Object addCommissionV3(OrderInfo orderInfo) {
        if (orderInfo.getShopID() == null || orderInfo.getShopID() == 0l) {//b2b订单不计算佣金
            return "success";
        }
        Long seconddeptUserID = 0L;//分部
        Long thirddeptUserID = 0L;//二级分部
        Long fourthdeptUserID = 0L;//支部

        Long employeeID = orderInfo.getSalesManagerID();//员工
        Long userID = orderInfo.getUserID();    //购买人
        Long salesID = orderInfo.getSalesID();//顾问
        Long storeManagerID = orderInfo.getStoreManagerID(); //店长160
        Long shopID = orderInfo.getShopID();//店铺shopID 商城ID
        Long branchID = orderInfo.getBranchID();//分部
        Long twoLevelBranchID = orderInfo.getTwoLevelBranchID();//二级分部
        Long subbranchID = orderInfo.getSubbranchID();//支部

        List<OrderPart> partList = new ArrayList<>();

        logger.info("................小商城成交奖金计算 ................... begin....");

        //判断购买人身份
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + userID, restTemplate);
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        if (storeManagerID != null && !Objects.equal(storeManagerID, 0L) && Objects.equal(userID, storeManagerID)) {//店长购买
            employeeID = userID;
            salesID = userID;
        } else if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 2)) {//员工购买
            employeeID = userID;
            salesID = userID;
            //合伙人自己购买
            if (Objects.equal(MapUtils.getInteger(userinfo, "shopID"), shopID)) {
                storeManagerID = userID;
            }
        } else if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 3)) {//顾问购买
            salesID = userID;
        } else if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 4) && (salesID == null || Objects.equal(salesID, 0L))) {//会员购买 &&  无顾问的情况
            salesID = employeeID;
        }

        //查找商城， 找店长和老板
        DataResult result = HttpUtil.httpGet(ProConstants.BASE + "/organizational/queryOrginfo/" + shopID, restTemplate);
        if (result.getIsSuccess() == 0 || result.getData() == null) {
            throw new ServiceException("未获取到商城、店铺资料");
        }
        Map<String, Object> orginfo = (Map<String, Object>) result.getData();

        ////当前分销商ID
        Long bossOrgID = Long.parseLong(orginfo.get("oID") + "");
        //当前分销商级别
        Integer distGrade = MapUtils.getInteger(orginfo, "level");
        //消费者归属商城id
        Long buyUserShopID = MapUtils.getLong(userinfo, "organizationalID");

        //奖金分成系数
        List<GoodsClassifyRebate> comminRebateList = null;
        Map<String, Object> rebateProfitMap = new HashMap<String, Object>();
        //消费者直接购买时，店铺才计算提成 2018-4-10
        if (buyUserShopID != null && bossOrgID != null && bossOrgID.equals(buyUserShopID)) {
            comminRebateList = rebateService.selectListBySellID(shopID, 2);
            if (comminRebateList == null || comminRebateList.isEmpty()) {
                //throw new ServiceException("店铺奖金系数未设置");
            }
            for (GoodsClassifyRebate goodsClassifyRebate : comminRebateList) {
                rebateProfitMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
            }
        }
        //平台商品分销提成
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("平台商品分销系数未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        //支部管理员
        if (subbranchID != null && !Objects.equal(subbranchID, 0L)) {//获取支部管理员
            fourthdeptUserID = getDeptAdmin(subbranchID);
        }
        //获取二级分部管理员
        if (twoLevelBranchID != null && !Objects.equal(twoLevelBranchID, 0L)) {//获取二级分部管理员
            thirddeptUserID = getDeptAdmin(twoLevelBranchID);
        }
        //获取分部管理员
        if (branchID != null && !Objects.equal(branchID, 0L)) {
            seconddeptUserID = getDeptAdmin(branchID);
        }
        //店铺奖金分配
        BigDecimal commEmploy = BigDecimal.valueOf(0);
        BigDecimal commStoreMng = BigDecimal.valueOf(0);
        BigDecimal commSalesMng = BigDecimal.valueOf(0);

        BigDecimal deductionRate = BigDecimal.valueOf(0);

        List<DealDto> dealDtos = new ArrayList<DealDto>();


        //订单明细
        List<Map<String, Object>> items = orderItemMapper.selectWithclassifyByOrderID(orderInfo.getOrderID());
        BigDecimal commissionGrade1 = BigDecimal.valueOf(0);
        BigDecimal commissionGrade2 = BigDecimal.valueOf(0);
        BigDecimal commissionGrade3 = BigDecimal.valueOf(0);
        String classifyID = "";

        
        //奖金 = 成交金额-店铺奖金-代理进货价
        for (Map<String, Object> item : items) {
            Integer qty = MapUtils.getInteger(item, "qty", 0);
            BigDecimal wholeSalePrice = BigDecimal.valueOf(MapUtils.getDouble(item, "wholeSalePrice", 0d));
            BigDecimal itemAmount = BigDecimal.valueOf(MapUtils.getDouble(item, "amount", 0d));

            BigDecimal amount = wholeSalePrice.multiply(BigDecimal.valueOf(qty));
            classifyID = MapUtils.getString(item, "subClassifyID", "");
            GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(classifyID);

            if (rebateProfitMap != null) {
                GoodsClassifyRebate rebateProfit = (GoodsClassifyRebate) rebateProfitMap.get(classifyID);
                //店铺奖金
                //1:代理商分成 2:店长分成  3:店员分成  4:顾问分成
                if (rebateProfit != null && rebateProfit.getBankVal() != null && rebateProfit.getEmployeeVal() != null) {
                    if (salesID != null && !Objects.equal(salesID, 0L)) {//顾问
                        commSalesMng = commSalesMng.add(itemAmount.multiply(new BigDecimal(rebateProfit.getThirdVal()).divide(new BigDecimal(1000))));
                    }
                    if (employeeID != null && !Objects.equal(employeeID, 0L)) {  //店员
                        commEmploy = commEmploy.add(itemAmount.multiply(new BigDecimal(rebateProfit.getEmployeeVal()).divide(new BigDecimal(1000))));
                    }
                    if (storeManagerID != null && !Objects.equal(storeManagerID, 0L)) {//店长
                        commStoreMng = commStoreMng.add(itemAmount.multiply(new BigDecimal(rebateProfit.getBankVal()).divide(new BigDecimal(1000))));
                    }
                }
            }

            if(rebate!=null && rebate.getDeductionRate()!=null){
                deductionRate = deductionRate.add(itemAmount.multiply(new BigDecimal(rebate.getDeductionRate()).divide(new BigDecimal(1000))));
            }

            String attrJson = MapUtils.getString(item, "attrJson", "");
            int priceType = MapUtils.getIntValue(item, "priceType", 0);

            //分销分成
            switch (distGrade.intValue()) {
                case 2:
                    //一级代理
                    if(priceType==1){
                        commissionGrade1 = commissionGrade1.add(getAgencyAdd(attrJson,rebate.getBankVal()));
                    }else{
                        commissionGrade1 = commissionGrade1.add(amount.multiply(BigDecimal.valueOf(rebate.getBankVal())));
                    }

                    break;
                case 3:
                    //二级代理
                    if(priceType==1){
                        commissionGrade1 = commissionGrade1.add(getAgencyAdd(attrJson,rebate.getBankVal()));
                        commissionGrade2 = commissionGrade2.add(getAgencyAdd(attrJson,rebate.getEmployeeVal()));
                    }else{
                        commissionGrade1 = commissionGrade1.add(amount.multiply(BigDecimal.valueOf(rebate.getBankVal())));
                        commissionGrade2 = commissionGrade2.add(amount.multiply(BigDecimal.valueOf(rebate.getEmployeeVal())));
                    }

                    break;
                case 4:
                    //三级代理
                    if(priceType==1){
                        commissionGrade1 = commissionGrade1.add(getAgencyAdd(attrJson,rebate.getBankVal()));
                        commissionGrade2 = commissionGrade2.add(getAgencyAdd(attrJson,rebate.getEmployeeVal()));
                        commissionGrade3 = commissionGrade3.add(getAgencyAdd(attrJson,rebate.getThirdVal()));
                    }else{
                        commissionGrade1 = commissionGrade1.add(amount.multiply(BigDecimal.valueOf(rebate.getBankVal())));
                        commissionGrade2 = commissionGrade2.add(amount.multiply(BigDecimal.valueOf(rebate.getEmployeeVal())));
                        commissionGrade3 = commissionGrade3.add(amount.multiply(BigDecimal.valueOf(rebate.getThirdVal())));
                    }

                    break;
            }

            OrderItem tm = new OrderItem();
            tm.setItemID(MapUtils.getLong(item, "itemID", 0l));
            tm.setAgentRate(rebate.getBankVal());
            tm.setDeductionRate(rebate.getDeductionRate());
            orderItemMapper.updateByPrimaryKeySelective(tm);

        }


        //1:代理商分成 2:店长分成  3:店员分成  4:顾问分成
        if (rebateProfitMap != null) {
            if (salesID != null && !Objects.equal(salesID, 0L) && commSalesMng.compareTo(BigDecimal.ZERO) == 1) {//顾问
                DealDto dealDto = saveToDbV201804Point(salesID, orderInfo, commSalesMng, CommissionEnum.salesCommission.getCode());//顾问
                dealDtos.add(dealDto);
            }
            if (employeeID != null && !Objects.equal(employeeID, 0L) && commEmploy.compareTo(BigDecimal.ZERO) == 1) {  //店员
                DealDto dealDto = saveToDbV201804Point(employeeID, orderInfo, commEmploy, CommissionEnum.salesManagerCommission.getCode());//店员
                dealDtos.add(dealDto);
            }
            if (storeManagerID != null && !Objects.equal(storeManagerID, 0L) && commStoreMng.compareTo(BigDecimal.ZERO) == 1) {//店长
                DealDto dealDto = saveToDbV201804Point(storeManagerID, orderInfo, commStoreMng, CommissionEnum.storeManagerCommission.getCode());//店长
                dealDtos.add(dealDto);
            }
        }
        BigDecimal tmp1, tmp2, tmp3, profit;
        switch (distGrade.intValue()) {
            case 2:
                //一级代理
                tmp1 = commissionGrade1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);//一级加价
                profit = orderInfo.getAmount().subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(tmp1).subtract(orderInfo.getDueAmount()).subtract(deductionRate);
                if (orderInfo.getTransactionFee() != null && profit.compareTo(orderInfo.getTransactionFee()) > 0) {
                    profit = profit.subtract(orderInfo.getTransactionFee());
                }
                if (seconddeptUserID != null && !Objects.equal(seconddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(seconddeptUserID, orderInfo, profit, CommissionEnum.shopProfit.getCode());
                    dealDtos.add(dealDto);
                }
                partList = getPartByOrder(null,null,null,commStoreMng,commEmploy,commSalesMng,tmp1,deductionRate,orderInfo.getTransactionFee(),profit,orderInfo.getOrderID());
                break;
            case 3:
                //二级代理
                tmp1 = commissionGrade1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                tmp2 = commissionGrade2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                if (seconddeptUserID != null && !Objects.equal(seconddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(seconddeptUserID, orderInfo, tmp2.subtract(tmp1), CommissionEnum.oneAgent.getCode());
                    dealDtos.add(dealDto);
                }
                profit = orderInfo.getAmount().subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(tmp2).subtract(orderInfo.getDueAmount()).subtract(deductionRate);
                if (orderInfo.getTransactionFee() != null && profit.compareTo(orderInfo.getTransactionFee()) > 0) {
                    profit = profit.subtract(orderInfo.getTransactionFee());
                }
                if (thirddeptUserID != null && !Objects.equal(thirddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(thirddeptUserID, orderInfo, profit, CommissionEnum.shopProfit.getCode());
                    dealDtos.add(dealDto);
                }
                partList = getPartByOrder(tmp2.subtract(tmp1),null,null,commStoreMng,commEmploy,commSalesMng,tmp1,deductionRate,orderInfo.getTransactionFee(),profit,orderInfo.getOrderID());
                break;
            case 4:
                //三级代理
                tmp1 = commissionGrade1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                tmp2 = commissionGrade2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                tmp3 = commissionGrade3.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                if (seconddeptUserID != null && !Objects.equal(seconddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(seconddeptUserID, orderInfo, tmp2.subtract(tmp1), CommissionEnum.oneAgent.getCode());
                    dealDtos.add(dealDto);
                }
                if (thirddeptUserID != null && !Objects.equal(thirddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(thirddeptUserID, orderInfo, tmp3.subtract(tmp2), CommissionEnum.twoAgent.getCode());
                    dealDtos.add(dealDto);
                }
                profit = orderInfo.getAmount().subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(tmp3).subtract(orderInfo.getDueAmount()).subtract(deductionRate);;
                if (orderInfo.getTransactionFee() != null && profit.compareTo(orderInfo.getTransactionFee()) > 0) {
                    profit = profit.subtract(orderInfo.getTransactionFee());
                }
                if (fourthdeptUserID != null && !Objects.equal(fourthdeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(fourthdeptUserID, orderInfo, profit, CommissionEnum.shopProfit.getCode());
                    dealDtos.add(dealDto);
                }
                partList = getPartByOrder(tmp2.subtract(tmp1),tmp3.subtract(tmp2),null,commStoreMng,commEmploy,commSalesMng,tmp1,deductionRate,orderInfo.getTransactionFee(),profit,orderInfo.getOrderID());
                break;
        }
        orderPartMapper.insertBatch(partList);
        DataResult result1 = HttpUtil.httpPost(ProConstants.setUseGoldenList, dealDtos, restTemplate);
        if (result1.getIsSuccess() == 0) {
            throw new ServiceException("调用point服务生成金豆失败", RestConst.ErrorCode.SERVICE_FAIL);
        }

        logger.info("................小商城成交奖金计算 ................... end....");
        return "success";
    }


    public BigDecimal getAgencyAdd(String skuAttrJson,Integer val){//获取平台加价
        //(工费*克重)*系数
        Map skuMap = JsonUtil.toMap(skuAttrJson);
        BigDecimal goldWeight = new BigDecimal(null == skuMap.get("weight") ? "0" : skuMap.get("weight").toString());
        BigDecimal craftFeeB = new BigDecimal(null == skuMap.get("wage") ? "0" : skuMap.get("wage").toString());
        BigDecimal fee= craftFeeB.multiply(goldWeight).multiply(BigDecimal.valueOf(val));
        return  fee;
    }
    private List<OrderPart> getPartByOrder(BigDecimal oneAgent, BigDecimal twoAgent, BigDecimal threeAgent, BigDecimal commStoreMng, BigDecimal commEmploy, BigDecimal commSalesMng, BigDecimal platAdd, BigDecimal deductionRate, BigDecimal transactionFee, BigDecimal profit,Long orderID) {
        List<OrderPart> listPart = new ArrayList<>();
        if(oneAgent!=null){
            OrderPart oneAgentObj = new OrderPart();
            oneAgentObj.setPartID(IdGen.get().nextId());
            oneAgentObj.setOrderID(orderID);
            oneAgentObj.setType(CommissionEnum.oneAgent.getCode());
            oneAgentObj.setVal(oneAgent);
            oneAgentObj.setRemark(CommissionEnum.oneAgent.getMsg());
            listPart.add(oneAgentObj);
        }

        if(twoAgent!=null){
            OrderPart twoAgentObj = new OrderPart();
            twoAgentObj.setPartID(IdGen.get().nextId());
            twoAgentObj.setOrderID(orderID);
            twoAgentObj.setType(CommissionEnum.twoAgent.getCode());
            twoAgentObj.setVal(twoAgent);
            twoAgentObj.setRemark(CommissionEnum.twoAgent.getMsg());
            listPart.add(twoAgentObj);
        }

        if(threeAgent!=null){
            OrderPart threeAgentObj = new OrderPart();
            threeAgentObj.setPartID(IdGen.get().nextId());
            threeAgentObj.setOrderID(orderID);
            threeAgentObj.setType(CommissionEnum.threeAgent.getCode());
            threeAgentObj.setVal(threeAgent);
            threeAgentObj.setRemark(CommissionEnum.threeAgent.getMsg());
            listPart.add(threeAgentObj);
        }

        if(commStoreMng !=null){
            OrderPart commStoreMngObj = new OrderPart();
            commStoreMngObj.setPartID(IdGen.get().nextId());
            commStoreMngObj.setOrderID(orderID);
            commStoreMngObj.setType(CommissionEnum.storeManagerCommission.getCode());
            commStoreMngObj.setVal(commStoreMng);
            commStoreMngObj.setRemark(CommissionEnum.storeManagerCommission.getMsg());
            listPart.add(commStoreMngObj);
        }

        if(commEmploy !=null){
            OrderPart commEmployObj = new OrderPart();
            commEmployObj.setPartID(IdGen.get().nextId());
            commEmployObj.setOrderID(orderID);
            commEmployObj.setType(CommissionEnum.salesManagerCommission.getCode());
            commEmployObj.setVal(commEmploy);
            commEmployObj.setRemark(CommissionEnum.salesManagerCommission.getMsg());
            listPart.add(commEmployObj);
        }

        if(commSalesMng !=null){
            OrderPart commSalesMngObj = new OrderPart();
            commSalesMngObj.setPartID(IdGen.get().nextId());
            commSalesMngObj.setOrderID(orderID);
            commSalesMngObj.setType(CommissionEnum.salesCommission.getCode());
            commSalesMngObj.setVal(commSalesMng);
            commSalesMngObj.setRemark(CommissionEnum.salesCommission.getMsg());
            listPart.add(commSalesMngObj);
        }

        if(platAdd !=null){
            OrderPart platAddObj = new OrderPart();
            platAddObj.setPartID(IdGen.get().nextId());
            platAddObj.setOrderID(orderID);
            platAddObj.setType(CommissionEnum.platAdd.getCode());
            platAddObj.setVal(platAdd);
            platAddObj.setRemark(CommissionEnum.platAdd.getMsg());
            listPart.add(platAddObj);
        }

        if(deductionRate !=null){
            OrderPart deductionRateObj = new OrderPart();
            deductionRateObj.setPartID(IdGen.get().nextId());
            deductionRateObj.setOrderID(orderID);
            deductionRateObj.setType(CommissionEnum.platDeduction.getCode());
            deductionRateObj.setVal(deductionRate);
            deductionRateObj.setRemark(CommissionEnum.platDeduction.getMsg());
            listPart.add(deductionRateObj);
        }

        if(transactionFee !=null){
            OrderPart transactionFeeObj = new OrderPart();
            transactionFeeObj.setPartID(IdGen.get().nextId());
            transactionFeeObj.setOrderID(orderID);
            transactionFeeObj.setType(CommissionEnum.transactionFee.getCode());
            transactionFeeObj.setVal(transactionFee);
            transactionFeeObj.setRemark(CommissionEnum.transactionFee.getMsg());
            listPart.add(transactionFeeObj);
        }

        if(profit !=null){
            OrderPart profitObj = new OrderPart();
            profitObj.setPartID(IdGen.get().nextId());
            profitObj.setOrderID(orderID);
            profitObj.setType(CommissionEnum.shopProfit.getCode());
            profitObj.setVal(profit);
            profitObj.setRemark(CommissionEnum.shopProfit.getMsg());
            listPart.add(profitObj);
        }

       return  listPart;


    }


    /**
     * 小商城成交奖金计算 2018-3-23
     * <p>
     * 计算方式  3-25-2018
     * 1. 店铺层级的奖金按照向下兼容的原则，以购买者所属的分销机构计算，即：层级高的可以拿完层级低
     * 2. 合伙人的奖金按照向上兼容的原则，以购买商城的合伙人结构计算，即：从层级低开始计算
     * 3. 消费者归属的商城与购买实际商城不一致时，计算系数参考购买的实际商城，计算分成人员参考归属的架构层级
     * <p>
     * <p>
     * <p>
     * 计算方式 4-10-2018
     * * 1. 用户直接购买： 店铺用户和供货渠道依次有提成
     * * 2. 用户间接购买： 即用户归属商城与购买商城不一致时，对购买商城的供货渠道进行提成计算
     * * 3. 6%o的手续费有购买商城负责
     *
     * @param orderInfo
     * @return
     */
    public Object addCommissionV2(OrderInfo orderInfo) {
        if (orderInfo.getShopID() == null || orderInfo.getShopID() == 0l) {//b2b订单不计算佣金
            return "success";
        }
        Long seconddeptUserID = 0L;//分部
        Long thirddeptUserID = 0L;//二级分部
        Long fourthdeptUserID = 0L;//支部

        Long employeeID = orderInfo.getSalesManagerID();//员工
        Long userID = orderInfo.getUserID();    //购买人
        Long salesID = orderInfo.getSalesID();//顾问
        Long storeManagerID = orderInfo.getStoreManagerID(); //店长160
        Long shopID = orderInfo.getShopID();//店铺shopID 商城ID
        Long branchID = orderInfo.getBranchID();//分部
        Long twoLevelBranchID = orderInfo.getTwoLevelBranchID();//二级分部
        Long subbranchID = orderInfo.getSubbranchID();//支部

        logger.info("................小商城成交奖金计算 ................... begin....");

        //判断购买人身份
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + userID, restTemplate);
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        if (storeManagerID != null && !Objects.equal(storeManagerID, 0L) && Objects.equal(userID, storeManagerID)) {//店长购买
            employeeID = userID;
            salesID = userID;
        } else if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 2)) {//员工购买
            employeeID = userID;
            salesID = userID;
            //合伙人自己购买
            if (Objects.equal(MapUtils.getInteger(userinfo, "shopID"), shopID)) {
                storeManagerID = userID;
            }
        } else if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 3)) {//顾问购买
            salesID = userID;
        } else if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 4) && (salesID == null || Objects.equal(salesID, 0L))) {//会员购买 &&  无顾问的情况
            salesID = employeeID;
        }

        //查找商城， 找店长和老板
        DataResult result = HttpUtil.httpGet(ProConstants.BASE + "/organizational/queryOrginfo/" + shopID, restTemplate);
        if (result.getIsSuccess() == 0 || result.getData() == null) {
            throw new ServiceException("未获取到商城、店铺资料");
        }
        Map<String, Object> orginfo = (Map<String, Object>) result.getData();

        ////当前分销商ID
        Long bossOrgID = Long.parseLong(orginfo.get("oID") + "");
        //当前分销商级别
        Integer distGrade = MapUtils.getInteger(orginfo, "level");
        //消费者归属商城id
        Long buyUserShopID = MapUtils.getLong(userinfo, "organizationalID");

        //奖金分成系数
        List<GoodsClassifyRebate> comminRebateList = null;
        Map<String, Object> rebateProfitMap = new HashMap<String, Object>();
        //消费者直接购买时，店铺才计算提成 2018-4-10
        if (buyUserShopID != null && bossOrgID != null && bossOrgID.equals(buyUserShopID)) {
            comminRebateList = rebateService.selectListBySellID(shopID, 2);
            if (comminRebateList == null || comminRebateList.isEmpty()) {
                //throw new ServiceException("店铺奖金系数未设置");
            }
            for (GoodsClassifyRebate goodsClassifyRebate : comminRebateList) {
                rebateProfitMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
            }
        }
        //平台商品分销提成
        List<GoodsClassifyRebate> distRebateList = rebateService.selectListBySellID(SystemContext.getCompanyID(), 1);
        if (distRebateList == null || distRebateList.isEmpty()) {
            throw new ServiceException("平台商品分销系数未设置");
        }
        Map<String, Object> rebateMap = new HashMap<String, Object>();
        for (GoodsClassifyRebate goodsClassifyRebate : distRebateList) {
            rebateMap.put(goodsClassifyRebate.getClazzID(), goodsClassifyRebate);
        }
        //支部管理员
        if (subbranchID != null && !Objects.equal(subbranchID, 0L)) {//获取支部管理员
            fourthdeptUserID = getDeptAdmin(subbranchID);
        }
        //获取二级分部管理员
        if (twoLevelBranchID != null && !Objects.equal(twoLevelBranchID, 0L)) {//获取二级分部管理员
            thirddeptUserID = getDeptAdmin(twoLevelBranchID);
        }
        //获取分部管理员
        if (branchID != null && !Objects.equal(branchID, 0L)) {
            seconddeptUserID = getDeptAdmin(branchID);
        }
        //店铺奖金分配
        BigDecimal commEmploy = BigDecimal.valueOf(0);
        BigDecimal commStoreMng = BigDecimal.valueOf(0);
        BigDecimal commSalesMng = BigDecimal.valueOf(0);

        List<DealDto> dealDtos = new ArrayList<DealDto>();


        //订单明细
        List<Map<String, Object>> items = orderItemMapper.selectWithclassifyByOrderID(orderInfo.getOrderID());
        BigDecimal commissionGrade1 = BigDecimal.valueOf(0);
        BigDecimal commissionGrade2 = BigDecimal.valueOf(0);
        BigDecimal commissionGrade3 = BigDecimal.valueOf(0);
        String classifyID = "";

        //奖金 = 成交金额-店铺奖金-代理进货价
        for (Map<String, Object> item : items) {
            Integer qty = MapUtils.getInteger(item, "qty", 0);
            BigDecimal suggestPrice = BigDecimal.valueOf(MapUtils.getDouble(item, "suggestPrice", 0d));
            BigDecimal itemAmount = BigDecimal.valueOf(MapUtils.getDouble(item, "amount", 0d));

            BigDecimal amount = suggestPrice.multiply(BigDecimal.valueOf(qty));
            classifyID = MapUtils.getString(item, "subClassifyID", "");
            GoodsClassifyRebate rebate = (GoodsClassifyRebate) rebateMap.get(classifyID);

            if (rebateProfitMap != null) {
                GoodsClassifyRebate rebateProfit = (GoodsClassifyRebate) rebateProfitMap.get(classifyID);
                //店铺奖金
                //1:代理商分成 2:店长分成  3:店员分成  4:顾问分成
                if (rebateProfit != null && rebateProfit.getBankVal() != null && rebateProfit.getEmployeeVal() != null) {
                    if (salesID != null && !Objects.equal(salesID, 0L)) {//顾问
                        commSalesMng = commSalesMng.add(itemAmount.multiply(new BigDecimal(rebateProfit.getThirdVal()).divide(new BigDecimal(1000))));
                    }
                    if (employeeID != null && !Objects.equal(employeeID, 0L)) {  //店员
                        commEmploy = commEmploy.add(itemAmount.multiply(new BigDecimal(rebateProfit.getEmployeeVal()).divide(new BigDecimal(1000))));
                    }
                    if (storeManagerID != null && !Objects.equal(storeManagerID, 0L)) {//店长
                        commStoreMng = commStoreMng.add(itemAmount.multiply(new BigDecimal(rebateProfit.getBankVal()).divide(new BigDecimal(1000))));
                    }
                }
            }
            //分销分成
            switch (distGrade.intValue()) {
                case 2:
                    //一级代理
                    commissionGrade1 = commissionGrade1.add(amount.multiply(BigDecimal.valueOf(rebate.getBankVal())));
                    break;
                case 3:
                    //二级代理
                    commissionGrade1 = commissionGrade1.add(amount.multiply(BigDecimal.valueOf(rebate.getBankVal())));
                    commissionGrade2 = commissionGrade2.add(amount.multiply(BigDecimal.valueOf(rebate.getEmployeeVal())));
                    break;
                case 4:
                    //三级代理
                    commissionGrade1 = commissionGrade1.add(amount.multiply(BigDecimal.valueOf(rebate.getBankVal())));
                    commissionGrade2 = commissionGrade2.add(amount.multiply(BigDecimal.valueOf(rebate.getEmployeeVal())));
                    commissionGrade3 = commissionGrade3.add(amount.multiply(BigDecimal.valueOf(rebate.getThirdVal())));
                    break;
            }
        }


        //1:代理商分成 2:店长分成  3:店员分成  4:顾问分成
        if (rebateProfitMap != null) {
            if (salesID != null && !Objects.equal(salesID, 0L) && commSalesMng.compareTo(BigDecimal.ZERO) == 1) {//顾问
                DealDto dealDto = saveToDbV201804Point(salesID, orderInfo, commSalesMng, CommissionEnum.salesCommission.getCode());//顾问
                dealDtos.add(dealDto);
            }
            if (employeeID != null && !Objects.equal(employeeID, 0L) && commEmploy.compareTo(BigDecimal.ZERO) == 1) {  //店员
                DealDto dealDto = saveToDbV201804Point(employeeID, orderInfo, commEmploy, CommissionEnum.salesManagerCommission.getCode());//店员
                dealDtos.add(dealDto);
            }
            if (storeManagerID != null && !Objects.equal(storeManagerID, 0L) && commStoreMng.compareTo(BigDecimal.ZERO) == 1) {//店长
                DealDto dealDto = saveToDbV201804Point(storeManagerID, orderInfo, commStoreMng, CommissionEnum.storeManagerCommission.getCode());//店长
                dealDtos.add(dealDto);
            }
        }
        BigDecimal tmp1, tmp2, tmp3, profit;
        switch (distGrade.intValue()) {
            case 2:
                //一级代理
                tmp1 = commissionGrade1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);//一级进货价
                profit = orderInfo.getAmount().subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(tmp1);
                if (orderInfo.getTransactionFee() != null && profit.compareTo(orderInfo.getTransactionFee()) > 0) {
                    profit = profit.subtract(orderInfo.getTransactionFee());
                }
                if (seconddeptUserID != null && !Objects.equal(seconddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(seconddeptUserID, orderInfo, profit, CommissionEnum.shopProfit.getCode());
                    dealDtos.add(dealDto);
                }
                break;
            case 3:
                //二级代理
                tmp1 = commissionGrade1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                tmp2 = commissionGrade2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                if (seconddeptUserID != null && !Objects.equal(seconddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(seconddeptUserID, orderInfo, tmp2.subtract(tmp1), CommissionEnum.oneAgent.getCode());
                    dealDtos.add(dealDto);
                }
                profit = orderInfo.getAmount().subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(tmp2);
                if (orderInfo.getTransactionFee() != null && profit.compareTo(orderInfo.getTransactionFee()) > 0) {
                    profit = profit.subtract(orderInfo.getTransactionFee());
                }
                if (thirddeptUserID != null && !Objects.equal(thirddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(thirddeptUserID, orderInfo, profit, CommissionEnum.shopProfit.getCode());
                    dealDtos.add(dealDto);
                }
                break;
            case 4:
                //三级代理
                tmp1 = commissionGrade1.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                tmp2 = commissionGrade2.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                tmp3 = commissionGrade3.divide(new BigDecimal(1000), 2, BigDecimal.ROUND_HALF_UP);
                if (seconddeptUserID != null && !Objects.equal(seconddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(seconddeptUserID, orderInfo, tmp2.subtract(tmp1), CommissionEnum.oneAgent.getCode());
                    dealDtos.add(dealDto);
                }
                if (thirddeptUserID != null && !Objects.equal(thirddeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(thirddeptUserID, orderInfo, tmp3.subtract(tmp2), CommissionEnum.twoAgent.getCode());
                    dealDtos.add(dealDto);
                }
                profit = orderInfo.getAmount().subtract(commEmploy).subtract(commStoreMng).subtract(commSalesMng).subtract(tmp3);
                if (orderInfo.getTransactionFee() != null && profit.compareTo(orderInfo.getTransactionFee()) > 0) {
                    profit = profit.subtract(orderInfo.getTransactionFee());
                }
                if (fourthdeptUserID != null && !Objects.equal(fourthdeptUserID, 0L)) {
                    DealDto dealDto = saveToDbV201804Point(fourthdeptUserID, orderInfo, profit, CommissionEnum.shopProfit.getCode());
                    dealDtos.add(dealDto);
                }
                break;
        }

        DataResult result1 = HttpUtil.httpPost(ProConstants.setUseGoldenList, dealDtos, restTemplate);
        if (result1.getIsSuccess() == 0) {
            throw new ServiceException("调用point服务生成金豆失败", RestConst.ErrorCode.SERVICE_FAIL);
        }

        logger.info("................小商城成交奖金计算 ................... end....");
        return "success";
    }


    private DealDto saveToDbV201804Point(Long salesID, OrderInfo orderInfo, BigDecimal commission, int genre) {
        DealDto dealDto = new DealDto();
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + salesID, restTemplate);
        if (userResult.getIsSuccess() == 0) {
            throw new ServiceException("调用base服务失败", RestConst.ErrorCode.SERVICE_FAIL);
        }
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        dealDto.setUserID(MapUtils.getString(userinfo, "userID"));
        dealDto.setUserType(MapUtils.getInteger(userinfo, "type"));
        dealDto.setUserName(MapUtils.getString(userinfo, "name"));
        dealDto.setUserTele(MapUtils.getString(userinfo, "mobile"));
        dealDto.setPayNo(orderInfo.getPayNo());
        dealDto.setAmount(commission);
        dealDto.setPoint(getPointByAmount(dealDto.getAmount()));
        dealDto.setSourceID(orderInfo.getOrderID());
        List<String> orders = new ArrayList<>();
        orders.add(orderInfo.getOrderNO());
        dealDto.setOrderNOS(orders);
        dealDto.setGenre(genre);
        return dealDto;
    }


    /**
     * 价钱转换成金豆
     *
     * @param amount
     * @return
     */
    private BigDecimal getPointByAmount(BigDecimal amount) {
        //获取实时金价
        JSONObject jsonObject = HttpUtil.httpGetJSONObject(ProConstants.getPointRealPrice, restTemplate);
        if (!com.google.common.base.Objects.equal(DataUtils.getInteger(jsonObject, "isSuccess"), 1)) {
            //throw new ServiceException("调用base服务获取实时金价接口出错", RestConst.ErrorCode.SERVICE_FAIL);
            return BigDecimal.ZERO;
        }
        BigDecimal gold = new BigDecimal(jsonObject.get("data").toString());
        BigDecimal point = BigDecimalUtil.div(amount, gold, 4).multiply(BigDecimal.valueOf(10000));
        return point;
    }


    private Object addCommission(OrderInfo orderInfo) {
        Long supplierID = 0L;//供应商
        Long topdeptUserID = 0L;//总部
        Long seconddeptUserID = 0L;//分部
        Long thirddeptUserID = 0L;//二级分部
        Long fourthdeptUserID = 0L;//支部
        Long employeeID = 0L;//员工
        Long salerID = 0L;//促销员

        Long userID = orderInfo.getUserID();    //会员
        Long salesID = orderInfo.getSalesID();  //促销员
        Long salesManagerID = orderInfo.getSalesManagerID();//销售经理
        Long branchID = orderInfo.getBranchID();//分部
        Long twoLevelBranchID = orderInfo.getTwoLevelBranchID();//二级分部
        Long subbranchID = orderInfo.getSubbranchID();//支部

        //获取供应商
        String url = new StringBuffer().append(ProConstants.getCompany).append(orderInfo.getSellerID()).toString();
        DataResult dataResult = HttpUtil.httpGet(url, restTemplate);
        if (!Objects.equal(dataResult.getIsSuccess(), 1)) {
            throw new ServiceException("未获取到供应商");
        }
        Map<String, Object> map = (Map<String, Object>) dataResult.getData();
        supplierID = MapUtils.getLong(map, "userID", 0L);//供应商管理者
        if (supplierID == null || Objects.equal(supplierID, 0L)) {
            throw new ServiceException("未获取到供应商管理者");
        }

        //判断会员身份
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + userID, restTemplate);
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        if (Objects.equal(MapUtils.getInteger(userinfo, "type"), 2)) {//员工
            //salerID = userID;//促销员是员工本人
            employeeID = userID;
        } else {//会员
            if (salesID == null || Objects.equal(salesID, 0L)) {//没有促销员
                if (salesManagerID == null || Objects.equal(salesManagerID, 0L)) {//没有找到员工即为总部会员
                    //未找到员工
                } else {
                    salerID = salesManagerID;
                    employeeID = salesManagerID;
                }
            } else {//有促销员
                salerID = salesID;
                if (salesManagerID == null || Objects.equal(salesManagerID, 0L)) {//没有找到员工即为总部会员
                    //未找到员工
                } else {
                    employeeID = salesManagerID;
                }
            }
        }

        //支部管理员
        if (subbranchID != null && !Objects.equal(subbranchID, 0L)) {//获取支部管理员
            fourthdeptUserID = getDeptAdmin(subbranchID);
        }
        //获取二级分部管理员
        if (twoLevelBranchID != null && !Objects.equal(twoLevelBranchID, 0L)) {//获取二级分部管理员
            thirddeptUserID = getDeptAdmin(twoLevelBranchID);
        }
        //获取分部管理员
        if (branchID != null && !Objects.equal(branchID, 0L)) {
            seconddeptUserID = getDeptAdmin(branchID);
        }
        //获取总部管理员
        Long topDeptID = TopDeptEnum.valuekOf(orderInfo.getCompanyID(), restTemplate).getDeptID();
        if (topDeptID != null && !Objects.equal(topDeptID, 0L)) {
            topdeptUserID = getDeptAdmin(topDeptID);
        }


        if (Objects.equal(seconddeptUserID, 0L)) {//分部、省代管理员
            seconddeptUserID = topdeptUserID;
        }
       /* if (Objects.equal(thirddeptUserID, 0L)) {//二级分部，市代管理员
            thirddeptUserID = seconddeptUserID;
        }*/
        if (Objects.equal(fourthdeptUserID, 0L)) {//支部、加盟店管理员
            //fourthdeptUserID = thirddeptUserID;
            fourthdeptUserID = seconddeptUserID;
        }
        if (Objects.equal(employeeID, 0L)) {//员工
            employeeID = topdeptUserID;
        }
        if (Objects.equal(salerID, 0L)) {//促销员
            salerID = employeeID;
        }

        //判断是否是加盟店老板或省代老板购买
        boolean isSecondDeptManager = false;
        boolean isThirdDeptManager = false;
        boolean isFourthDeptManager = false;
        //省代购买
        if (Objects.equal(seconddeptUserID, userID)) {
            isSecondDeptManager = true;
        }
        //市代购买
        if (Objects.equal(seconddeptUserID, userID)) {
            isThirdDeptManager = true;
        }
        //加盟店购买
        if (Objects.equal(fourthdeptUserID, userID)) {
            isFourthDeptManager = true;
        }

        //订单明细
        List<Map<String, Object>> items = orderItemMapper.selectWithclassifyByOrderID(orderInfo.getOrderID());
        for (Map<String, Object> item : items) {
            GoodsClassifyCommission goodsClassifyCommission = getClassifyCommission(orderInfo, item);
            if (isSecondDeptManager) {//省代购买
                //按原价分成
                orderInfo.setAmount(BigDecimalUtil.add(orderInfo.getAmount(), orderInfo.getPointAmount()));//计算原价
                Double price = MapUtils.getDouble(item, "price", 0d);//商品金额
                Integer qty = MapUtils.getInteger(item, "qty", 0);
                item.put("amount", price * qty);//计算原价
                assignCommissionForDeptAdmin(orderInfo, item, userID, BuyerEnum.SECONDDEPT.getsFlag(), goodsClassifyCommission);
                assignCommission(orderInfo, item, topdeptUserID, BuyerEnum.TOPDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, supplierID, BuyerEnum.SUPPLIER.getsFlag(), 4, goodsClassifyCommission);
            } else if (isFourthDeptManager) {//加盟店购买
                //按原价分成
                orderInfo.setAmount(BigDecimalUtil.add(orderInfo.getAmount(), orderInfo.getPointAmount()));//计算原价
                Double price = MapUtils.getDouble(item, "price", 0d);//商品单价
                Integer qty = MapUtils.getInteger(item, "qty", 0);
                item.put("amount", price * qty);//计算原价
                assignCommissionForDeptAdmin(orderInfo, item, userID, BuyerEnum.FOURTHDEPT.getsFlag(), goodsClassifyCommission);
                //assignCommission(orderInfo, item, thirddeptUserID, BuyerEnum.THIRDDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, seconddeptUserID, BuyerEnum.SECONDDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, topdeptUserID, BuyerEnum.TOPDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, supplierID, BuyerEnum.SUPPLIER.getsFlag(), 4, goodsClassifyCommission);
            } else {
                //按实际支付金额分成
                assignCommission(orderInfo, item, salerID, BuyerEnum.SALER.getsFlag(), 1, goodsClassifyCommission);
                assignCommission(orderInfo, item, employeeID, BuyerEnum.EMPLOYEE.getsFlag(), 2, goodsClassifyCommission);
                assignCommission(orderInfo, item, fourthdeptUserID, BuyerEnum.FOURTHDEPT.getsFlag(), 3, goodsClassifyCommission);
                //assignCommission(orderInfo, item, thirddeptUserID, BuyerEnum.THIRDDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, seconddeptUserID, BuyerEnum.SECONDDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, topdeptUserID, BuyerEnum.TOPDEPT.getsFlag(), 3, goodsClassifyCommission);
                assignCommission(orderInfo, item, supplierID, BuyerEnum.SUPPLIER.getsFlag(), 4, goodsClassifyCommission);
            }

        }
        return "success";
    }


    private void assignCommissionForDeptAdmin(OrderInfo orderInfo, Map<String, Object> item, Long userID, String cUser, GoodsClassifyCommission goodsClassifyCommission) {
        String commissionRate = goodsClassifyCommission.getCommissionRate();//奖金分配规则,json
        String taxRate = goodsClassifyCommission.getTaxRate();//税点,json
        if (Strings.isNullOrEmpty(commissionRate) || !commissionRate.startsWith("{")) {
            //throw new ServiceException("未获取到奖金分配规则");
            return;
        }
        Map<String, Object> commissionRateMap = JsonUtil.toMap(commissionRate);
        Double amount = MapUtils.getDouble(item, "amount", 0d);//商品金额
        //获取分配比例
        Double supplierProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.SUPPLIER.getsFlag(), 0d);
        Double topdeptProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.TOPDEPT.getsFlag(), 0d);
        Double seconddeptProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.SECONDDEPT.getsFlag(), 0d);
        Double thirddeptProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.THIRDDEPT.getsFlag(), 0d);

        Double proportion = 1 - supplierProportion - topdeptProportion;
        if (Objects.equal(cUser, BuyerEnum.SECONDDEPT.getsFlag())) {//省代购买
            proportion = 1 - supplierProportion - topdeptProportion;
        }
        // 市代没有优惠
        if (Objects.equal(cUser, BuyerEnum.THIRDDEPT.getsFlag())) {
            //proportion = 1 - supplierProportion - topdeptProportion - seconddeptProportion;
            proportion = 0d;
        }
        if (Objects.equal(cUser, BuyerEnum.FOURTHDEPT.getsFlag())) {
            proportion = proportion - seconddeptProportion - thirddeptProportion;
        }
        if (amount == 0 || proportion == 0) {
            return;
        }
        //获得奖金
        if (Objects.equal(orderInfo.getCouponType(), "4")) {
            BigDecimal gMoney = BigDecimalUtil.mul(orderInfo.getPointAmount(), BigDecimal.valueOf(1));//优惠金额
            BigDecimal commissionBigDecimal = BigDecimalUtil.sub(gMoney, BigDecimal.valueOf(0));
            Long commission = BigDecimalUtil.mul(commissionBigDecimal, BigDecimal.valueOf(1000)).longValue();
            saveToDb(userID, 0d, orderInfo, gMoney, commission, cUser, commissionRate, 3, "2");
        } else {
            BigDecimal gMoney = BigDecimalUtil.mul(BigDecimal.valueOf(amount), BigDecimal.valueOf(proportion));
            BigDecimal commissionBigDecimal = BigDecimalUtil.sub(gMoney, BigDecimal.valueOf(0));
            Long commission = BigDecimalUtil.mul(commissionBigDecimal, BigDecimal.valueOf(1000)).longValue();
            saveToDb(userID, 0d, orderInfo, gMoney, commission, cUser, commissionRate, 3, "2");
        }
    }

    /**
     * 获取省代或加盟店的折扣金额
     *
     * @param goodsClassifyCommission
     * @param isSecondDeptAdmin
     * @param isFourthDeptAdmin
     * @return
     */
    private Double getProportion(GoodsClassifyCommission goodsClassifyCommission, boolean isSecondDeptAdmin, boolean isFourthDeptAdmin) {
        String commissionRate = goodsClassifyCommission.getCommissionRate();//奖金分配规则,json
        if (Strings.isNullOrEmpty(commissionRate) || !commissionRate.startsWith("{")) {
            //throw new ServiceException("未获取到奖金分配规则");
            return 1d;
        }
        Map<String, Object> commissionRateMap = JsonUtil.toMap(commissionRate);
        //获取分配比例
        Double supplierProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.SUPPLIER.getsFlag(), 0d);
        Double topdeptProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.TOPDEPT.getsFlag(), 0d);
        Double seconddeptProportion = MapUtils.getDouble(commissionRateMap, BuyerEnum.SECONDDEPT.getsFlag(), 0d);

        Double proportion = 0d;
        if (isFourthDeptAdmin) {
            proportion = supplierProportion + topdeptProportion + seconddeptProportion;
        }
        if (isSecondDeptAdmin) {
            proportion = supplierProportion + topdeptProportion;
        }
        if (proportion == 0) {
            return 1d;
        }
        return proportion;
    }

    /**
     * @param orderInfo               订单信息
     * @param item                    订单明细
     * @param userID                  用户
     * @param cUser                   用户身份（参考BuyerEnum.java）
     * @param goodsClassifyCommission
     */
    private void assignCommission(OrderInfo orderInfo, Map<String, Object> item, Long userID, String cUser, Integer userType,
                                  GoodsClassifyCommission goodsClassifyCommission) {
        String commissionRate = goodsClassifyCommission.getCommissionRate();//奖金分配规则,json
        String taxRate = goodsClassifyCommission.getTaxRate();//税点,json
        if (Strings.isNullOrEmpty(commissionRate) || !commissionRate.startsWith("{")) {
            //throw new ServiceException("未获取到奖金分配规则");
            return;
        }
        Map<String, Object> commissionRateMap = JsonUtil.toMap(commissionRate);
        Map<String, Object> taxRateMap = JsonUtil.toMap(taxRate);
        Double amount = MapUtils.getDouble(item, "amount", 0d);//商品金额
        //获取分配比例
        Double proportion = MapUtils.getDouble(commissionRateMap, cUser, 0d);
        if (amount == 0 || proportion == 0) {
            return;
        }
        //获得奖金
        BigDecimal gMoney = BigDecimalUtil.mul(BigDecimal.valueOf(amount), BigDecimal.valueOf(proportion));
        //获取扣税比例
        Double tax = MapUtils.getDouble(taxRateMap, cUser, 0d);
        BigDecimal taxMoney = BigDecimal.valueOf(0);
        if (BuyerEnum.isCountTaxRate(cUser)) {//是否扣税
            taxMoney = BigDecimalUtil.mul(gMoney, BigDecimal.valueOf(tax));//扣税金额
        }
        BigDecimal commissionBigDecimal = BigDecimalUtil.sub(gMoney, taxMoney);
        Long commission = BigDecimalUtil.mul(commissionBigDecimal, BigDecimal.valueOf(1000)).longValue();
        saveToDb(userID, tax, orderInfo, gMoney, commission, cUser, commissionRate, userType, "1");
    }


    private void saveToDbV201803(Long userID, OrderInfo orderInfo, BigDecimal gMoney, Integer userType, Long commission, String type, String remark) {
        Map<String, Object> userMap = getUserInfo(userID);
        CommissionDetail detail = new CommissionDetail();
        detail.setCommissionDetailId(IdGen.get().nextId());
        detail.setUserId(userID);
        detail.setUserName(MapUtils.getString(userMap, "name", ""));
        detail.setOrderAmount((orderInfo.getAmount()).multiply(new BigDecimal(1000)).longValue());
        //detail.setTaxRate(BigDecimalUtil.mul(BigDecimal.valueOf(tax), BigDecimal.valueOf(1000)).longValue());//加盟店老板，员工，促销员，员工会扣税
        detail.setTotalCommission(BigDecimalUtil.mul(gMoney, BigDecimal.valueOf(1000)).longValue());//提成金额
        detail.setCommission(commission);//奖金
        detail.setType(type);//类型 1：获取 2:消费 3 提现
        detail.setStatus("1");//状态 1:可用 0:不可用
        detail.setPayNo(orderInfo.getPayNo());
        detail.setOrderNo(orderInfo.getOrderNO());
        detail.setExtJSON(new StringBuffer().append(orderInfo.getOrderID()).toString());
        detail.setRemark(remark);
        detail.setHandleUserId("0");//处理人
        detail.setHandleTime(System.currentTimeMillis());
        detail.setCompanyID(SystemContext.getCompanyID());

        CommissionUser _commissionUser = commissionUserMapper.selectByUserID(userID);
        if (Objects.equal(type, "1")) {//获取
            if (_commissionUser == null) {
                CommissionUser commissionUser = new CommissionUser();
                commissionUser.setUserCommissionID(IdGen.get().nextId());
                commissionUser.setUserId(detail.getUserId());
                commissionUser.setUserType(userType);//1 普通用户，2 销售经理、3管理者、4供应商管理者
                commissionUser.setUserName(MapUtils.getString(userMap, "name", ""));
                commissionUser.setUserTele(MapUtils.getString(userMap, "mobile", ""));
                commissionUser.setTotal(detail.getCommission());
                commissionUser.setLastTime(System.currentTimeMillis());
                commissionUser.setCompanyID(orderInfo.getCompanyID());
                String md5 = CommonUtils.MD5(commissionUser.getTotal().toString() + ProConstants.salt);
                commissionUser.setMd5(md5);
                commissionUserMapper.insertSelective(commissionUser);
                detail.setBalance(commissionUser.getTotal());//当前结余
            } else {
                CommissionUser commissionUser = new CommissionUser();
                commissionUser.setUserCommissionID(_commissionUser.getUserCommissionID());
                commissionUser.setTotal(_commissionUser.getTotal() + detail.getCommission());
                String md5 = CommonUtils.MD5(commissionUser.getTotal().toString() + ProConstants.salt);
                commissionUser.setMd5(md5);
                commissionUser.setLastTime(System.currentTimeMillis());
                int rows = commissionUserMapper.addCommission(commissionUser.getUserCommissionID(),
                        detail.getCommission(), commissionUser.getLastTime(), md5, null);
                if (rows == 0) {
                    throw new ServiceException("奖金分配失败");
                }
                detail.setBalance(commissionUser.getTotal());//当前结余
            }
        } else {//直接抵扣
            detail.setBalance(_commissionUser != null ? _commissionUser.getTotal() : 0L);
        }

        commissionDetailMapper.insertSelective(detail);
    }


    private void saveToDb(Long userID, Double tax, OrderInfo orderInfo, BigDecimal gMoney, Long commission, String cUser,
                          String commissionRate, Integer userType, String type) {
        Map<String, Object> userMap = getUserInfo(userID);
        CommissionDetail detail = new CommissionDetail();
        detail.setCommissionDetailId(IdGen.get().nextId());
        detail.setUserId(userID);
        detail.setUserName(MapUtils.getString(userMap, "name", ""));
        //detail.setOrderAmount((BigDecimal.valueOf(oA).multiply(new BigDecimal(1000)).longValue()));
        detail.setOrderAmount((orderInfo.getAmount()).multiply(new BigDecimal(1000)).longValue());
        detail.setTaxRate(BigDecimalUtil.mul(BigDecimal.valueOf(tax), BigDecimal.valueOf(1000)).longValue());//加盟店老板，员工，促销员，员工会扣税
        detail.setTotalCommission(BigDecimalUtil.mul(gMoney, BigDecimal.valueOf(1000)).longValue());//提成金额
        detail.setCommission(commission);//奖金
        detail.setType(type);//类型 1：获取 2:消费 3 提现
        detail.setStatus("1");//状态 1:可用 0:不可用
        detail.setPayNo(orderInfo.getPayNo());
        detail.setOrderNo(orderInfo.getOrderNO());
        detail.setExtJSON(commissionRate);

        detail.setRemark(new StringBuffer().append(cUser).append(",").append(orderInfo.getOrderID()).toString());//暂时存储用户身份
        detail.setHandleUserId("0");//处理人
        detail.setHandleTime(System.currentTimeMillis());

        CommissionUser _commissionUser = commissionUserMapper.selectByUserID(userID);
        if (Objects.equal(type, "1")) {//获取
            if (_commissionUser == null) {
                CommissionUser commissionUser = new CommissionUser();
                commissionUser.setUserCommissionID(IdGen.get().nextId());
                commissionUser.setUserId(detail.getUserId());
                commissionUser.setUserType(userType);//1普通用户，2销售经理、3管理者、4供应商管理者
                commissionUser.setUserName(MapUtils.getString(userMap, "name", ""));
                commissionUser.setUserTele(MapUtils.getString(userMap, "mobile", ""));
                commissionUser.setTotal(detail.getCommission());
                commissionUser.setLastTime(System.currentTimeMillis());
                commissionUser.setCompanyID(orderInfo.getCompanyID());
                String md5 = CommonUtils.MD5(commissionUser.getTotal().toString() + ProConstants.salt);
                commissionUser.setMd5(md5);
                commissionUserMapper.insertSelective(commissionUser);
                detail.setBalance(commissionUser.getTotal());//当前结余
            } else {
                CommissionUser commissionUser = new CommissionUser();
                commissionUser.setUserCommissionID(_commissionUser.getUserCommissionID());
                commissionUser.setTotal(_commissionUser.getTotal() + detail.getCommission());
                String md5 = CommonUtils.MD5(commissionUser.getTotal().toString() + ProConstants.salt);
                commissionUser.setMd5(md5);
                commissionUser.setLastTime(System.currentTimeMillis());
                int rows = commissionUserMapper.addCommission(commissionUser.getUserCommissionID(),
                        detail.getCommission(), commissionUser.getLastTime(), md5, null);
                if (rows == 0) {
                    throw new ServiceException("奖金分配失败");
                }
                detail.setBalance(commissionUser.getTotal());//当前结余
            }
        } else {//直接抵扣
            detail.setBalance(_commissionUser != null ? _commissionUser.getTotal() : 0L);
        }

        commissionDetailMapper.insertSelective(detail);
    }

    private Map<String, Object> getUserInfo(Long userID) {
        //判断会员身份
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserByID + userID, restTemplate);
        if (!Objects.equal(userResult.getIsSuccess(), 1)) {
            throw new ServiceException("未获取到用户信息");
        }
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        return userinfo;
    }

    private Map<String, Object> getUserInfoWithDept(Long userID) {
        //判断会员身份
        DataResult userResult = HttpUtil.httpGet(ProConstants.getUserWithDeptByID + userID, restTemplate);
        if (!Objects.equal(userResult.getIsSuccess(), 1) || userResult.getData() == null) {
            throw new ServiceException("未获取到用户信息");
        }
        Map<String, Object> userinfo = (Map<String, Object>) userResult.getData();
        return userinfo;
    }

    private Long getDeptAdmin(Long deptID) {
        DataResult result = HttpUtil.httpGet(ProConstants.getOrganizational + deptID, restTemplate);
        if (!Objects.equal(result.getIsSuccess(), 1)) {
            //throw new ServiceException("未获到部门数据数据");
            //return -1L;
            return 0L;
        }
        Map<String, Object> map = (Map<String, Object>) result.getData();
        Long adminID = MapUtils.getLong(map, "adminID", 0L);
        if (Objects.equal(adminID, 0L)) {
            //throw new ServiceException("未获取管理员数据");
            //return 0L;
            return 0L;
        }
        return adminID;
    }

    private GoodsClassifyCommission getClassifyCommission(OrderInfo orderInfo, Map<String, Object> item) {
        return getClassifyCommission(getClassify(item), orderInfo.getCompanyID());
    }

    private String getClassify(Map<String, Object> item) {
        String classifyID = MapUtils.getString(item, "classifyID");
        String subClassifyID = MapUtils.getString(item, "subClassifyID");
        String threeClassifyID = MapUtils.getString(item, "threeClassifyID");
        String fourClassifyID = MapUtils.getString(item, "fourClassifyID");

        if (!Strings.isNullOrEmpty(fourClassifyID)) {
            return fourClassifyID;
        }

        if (!Strings.isNullOrEmpty(threeClassifyID)) {
            return threeClassifyID;
        }

        if (!Strings.isNullOrEmpty(subClassifyID)) {
            return subClassifyID;
        }

        if (!Strings.isNullOrEmpty(classifyID)) {
            return classifyID;
        }

        return null;
    }

    //common
    private GoodsClassifyCommission getClassifyCommission(String classify, Long companyID) {
        if (Strings.isNullOrEmpty(classify)) {
            throw new ServiceException("未获取到商品分类");
        }
        GoodsClassifyCommission goodsClassifyCommission = goodsClassifyCommissionMapper.selectModelByClazzID(classify, companyID);
        if (goodsClassifyCommission == null) {
            throw new ServiceException("未获取到奖金分配规则");
        }
        return goodsClassifyCommission;
    }

    //商品相关
    private GoodsClassifyCommission getClassifyCommission(GoodsInfo goodsInfo) {
        return getClassifyCommission(getClassify(goodsInfo), goodsInfo.getCompanyID());
    }

    private String getClassify(GoodsInfo goodsInfo) {
        String classifyID = goodsInfo.getClassifyID();
        String subClassifyID = goodsInfo.getSubClassifyID();
        String threeClassifyID = goodsInfo.getThreeClassifyID();
        String fourClassifyID = goodsInfo.getFourClassifyID();

        if (!Strings.isNullOrEmpty(fourClassifyID)) {
            return fourClassifyID;
        }
        if (!Strings.isNullOrEmpty(threeClassifyID)) {
            return threeClassifyID;
        }
        if (!Strings.isNullOrEmpty(subClassifyID)) {
            return subClassifyID;
        }
        if (!Strings.isNullOrEmpty(classifyID)) {
            return classifyID;
        }
        return null;
    }

    /**
     * 补单时用
     *
     * @param ids
     * @return
     */
    public Object handErrorOrder(String ids) {
        if (Strings.isNullOrEmpty(ids)) {
            return "未获取到订单号";
        }
        String idArr[] = ids.split(",");
        int len = idArr.length;
        for (int i = 0; i < len; i++) {
            String id = idArr[i];
            if (!Strings.isNullOrEmpty(id)) {
                Long idL = Longs.tryParse(id);
                OrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(idL);
                Double oA = orderInfoMapper.selAmountByPayNo(orderInfo.getPayNo());
                addCommissionV3(orderInfo);
            }
        }
        return "success";
    }


    /**
     * 按条件查询分销商/店铺/员工的佣金列表信息
     *
     * @param pageNum
     * @param pageSize
     * @param selectDto
     * @return
     */
    public PageInfo selectShopListByCondition(int pageNum, int pageSize, UserCommissionDto selectDto) {
        // selectDto.setCompanyID(SystemContext.getCompanyID());
        PageHelper.startPage(pageNum, pageSize);
        selectDto.setDbUser(databaseTableUser);
        List<Map<String, Object>> companyInfoList = commissionDetailMapper.getCommDetailListByCond(selectDto);
        PageInfo<Map<String, Object>> page = new PageInfo(companyInfoList);
        return page;
    }


    /**
     * 导出明细
     *
     * @param map
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public List<Map<String, String>> exportDetail(Map map, UserCommissionDto selectDto, HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Map<String, String>> list = new ArrayList<>();
        try {
            List<Map<String, Object>> companyInfoList = commissionDetailMapper.getCommDetailListByCond(selectDto);
            list = orderInfoMapper.exportOrderDetail(map);
            ExportExcel.excelWrite(map, list, ProConstants.EXPORT_ORDER_DETAIL + "_" + CommonUtils.getCurTimestamp(), request, response);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
        return list;
    }

    public String getDatabaseTableUser() {
        return databaseTableUser;
    }

    public void setDatabaseTableUser(String databaseTableUser) {
        this.databaseTableUser = databaseTableUser;
    }
}
